package cn.bigfire.wzdj.net;

import cn.bigfire.wzdj.pojo.bo.WZDJPack;
import cn.bigfire.wzdj.util.ByteUtil;
import cn.bigfire.wzdj.util.PackUtil;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageDecoder;
import io.netty.handler.codec.http.websocketx.BinaryWebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketFrame;
import lombok.extern.slf4j.Slf4j;

import java.util.List;

/**
 * 业务层 编解码器
 */
@Slf4j
public class WZDJPackWSDecoder extends MessageToMessageDecoder<WebSocketFrame> {

    @Override
    protected void decode(ChannelHandlerContext ctx, WebSocketFrame msg, List<Object> out) throws Exception {
        try {
            if (msg instanceof BinaryWebSocketFrame) {
                BinaryWebSocketFrame binaryWebSocketFrame = (BinaryWebSocketFrame) msg;
                ByteBuf content = binaryWebSocketFrame.content();
                byte[] bytes = new byte[content.readableBytes()];
                content.readBytes(bytes);
                List<WZDJPack<?>> packList = PackUtil.decodeBytes(bytes);
                //打印
//                int length = bytes.length;
//                WZDJPack<?> wzdjPack = packList.get(0);
//                System.out.printf("<-cmd:%s,type:%s,len:%s[%s]%n", wzdjPack.getHeader().getId(),
//                        wzdjPack.getHeader().getName(), length, ByteUtil.getSize(length));

                for (WZDJPack<?> pack : packList) {
                    out.add(pack);
                }
            } else {
                log.error("不能解码的类型" + msg.getClass().getName());
//                log.error("不能解码的类型" + msg.getClass().getName());
                return;
            }


        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
